/**
 * VueRouter 类实现：
 * 1. 属性：options, 传入的路由配置
 *         routeMap, 路径和组件映射
 *         data.current, 当前路由地址
 * 2. 静态方法：install, 全局混入，挂载 $router 属性。
 * 3. 私有方法：createRouteMap, 生产路径和组件的映射关系
 *             initComponent, router-link 和 router-view 组件
 *             initEvent, 监听 popstate/hashchange, 路径变化修改 data.current 更新视图
 */

let _Vue = null;

export default class VueRouter {
  // 插件静态方法 install
  static install(Vue) {
    if (VueRouter.install.installed) {
      return;
    }
    VueRouter.install.installed = true;
    _Vue = Vue;
    _Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router;
        }
      }
    });
  }
  constructor(options) {
    this.options = options;
    this.routeMap = {};
    // 当前路由地址 响应式处理
    this.data = _Vue.observable({
      current: "/"
    });
    this._init();
  }
  _init() {
    this.createRouteMap();
    this.initComponent(_Vue);
    this.initEvent();
  }
  _createRouteMap() {
    // 记录路径和组件的映射关系
    this.options.routes.forEach(route => {
      this.routeMap[route.path] = route.component;
    });
  }
  _initComponent(Vue) {
    const self = this;

    Vue.component("router-link", {
      props: {
        to: String
      },
      render(h) {
        return h(
          "a",
          {
            attrs: {
              href: this.to
            },
            on: {
              click: this.clickHandler
            }
          },
          [this.$slots.default]
        );
      },
      methods: {
        clickHandler(e) {
          if (self.options.mode === "history") {
            history.pushState({}, "", this.to);
          } else {
            location.hash = "#" + this.to;
          }
          this.$router.data.current = this.to;
          e.preventDefault();
        }
      }
    });

    Vue.component("router-view", {
      render(h) {
        const component = self.routeMap[self.data.current];
        return h(component);
      }
    });
  }
  _initEvent() {
    // 路径变化时，修改当前路由地址，更新视图组件
    if (this.options.mode === "history") {
      window.addEventListener("popstate", () => {
        this.data.current = window.location.pathname;
      });
    } else {
      window.addEventListener("hashchange", () => {
        this.data.current = location.hash.slice(1) || "/";
      });
    }
  }
}
